<script setup>
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import * as pdfjsLib from "pdfjs-dist";

const route = useRoute();
const props = defineProps(["url", "height"]);
const heightValue = ref(props.height);
const value = ref("2024-02-10");
const options = [{ label: "2024-02-10", value: "2024-02-10" }];

const copyHtml = import.meta.env.VITE_CAS_URL+"/html/document"+decodeURI(route.path)

// const CM20240408 = "http://localhost:18888" + import.meta.env.BASE_URL + "static/pdf/CM20240408.pdf"; // 修改为您的 PDF 文件的路径

const scrollHeight = computed(() => {
  const height = Number(props.height) + 60;
  return `height: calc(100vh - ${height}px)`;
});

console.log(scrollHeight.value);

// 引入工作环境 重要
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.js",import.meta.url).href;

const pdfScale = ref(0.7); // 关键！如果清晰度不行，慢慢调整这个数值。
const pdfDoc = ref(null);
const numPages = ref(0); // pdf一共多少页
const nums = ref(1); // 循环加载的参数
const currentNum = ref(1); // 当前页数
const inpDisabled = ref(true); // pad文件没有加载完所有页数则禁用
const imgSrcList = ref([]); // 存储paf每一页
const pdfList = ref([])
const watermarkPoint = [
  [-120, -66],
  [-120, 66],
  [120, -66],
  [120, 66],
]; // 水印坐标
let pageHeight = null; // 每一页高度
let pdfWrap = null;
let isChangeCurrentNum = false;

// const query = new URLSearchParams(route.fullPath.split("?")[1]); // 从url地址栏获取水印文本信息
// const watermarkText = query.get("text"); // 自定义的水印文本
const watermarkText = "钱大妈"

// url为pdf链接
const loadingTask = pdfjsLib.getDocument(props.url);

// dom加载之后
onMounted(() => {
  pdfWrap = document.getElementById("pdf");
  togglePage(nums.value);
});

watch(
  () => nums.value,
  (num) => {
    if (num <= numPages.value) {
      togglePage(num);
    } else {
      inpDisabled.value = false;
    }
  }
);

async function togglePage(pageNumber = 1) {
  loadingTask.promise.then((pdf)=>{

      numPages.value = pdf.numPages

      pdf.getPage(pageNumber).then((page) => {

        const canvasId = "the-canvas" + pageNumber;
        const canvas = document.getElementById(canvasId);
        const context = canvas.getContext("2d");
        const dpr = window.devicePixelRatio || 1;
        const bsr =
          context.webkitBackingStorePixelRatio ||
          context.mozBackingStorePixelRatio ||
          context.msBackingStorePixelRatio ||
          context.oBackingStorePixelRatio ||
          context.backingStorePixelRatio ||
          1;
        const ratio = dpr / bsr;
        const viewport = page.getViewport({ scale: pdfScale.value });
        canvas.width = viewport.width * ratio;
        canvas.height = viewport.height * ratio;
        canvas.style.width = viewport.width + "px";
        canvas.style.height = viewport.height + "px";
        context.setTransform(ratio, 0, 0, ratio, 0, 0);
        
        

        // 只赋值一次
        !pageHeight && (pageHeight = (viewport.height * pdfScale.value).toFixed(2));

        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        };
        page.render(renderContext).promise.then(() => {
          // 添加水印
          context.font = `${16 / pdfScale.value}px Microsoft Yahei`;
          context.fillStyle = "rgba(0, 0, 0, .1)";
          context.textAlign = "center";
          context.textBaseline = "middle";
          // 设置自定义文本位于每一页pdf的空间位置
          watermarkPoint.forEach((point) => {
            context.translate(
              ((viewport.width * pdfScale.value) / 2 + point[0]) / pdfScale.value,
              ((viewport.height * pdfScale.value) / 2 + point[1]) / pdfScale.value
            );
            context.rotate((-30 * Math.PI) / 180);
            context.fillText(watermarkText, 0, 0);
          });
        })

        imgSrcList.value.push(canvas.toDataURL());
        // 完成 页码+1
        nums.value++;

      });
    },
    function (reason) {
      console.error(reason);
    }
  );
}

function handleScroll(e) {
  if (!isChangeCurrentNum) {
    const current = e.target.scrollTop / pageHeight;
    currentNum.value = Math.ceil(current === 0 ? 1 : current);
  }
  isChangeCurrentNum = false;
}

function handleBeforePage() {
  currentNum.value = currentNum.value - 1 <= 0 ? 1 : currentNum.value - 1;
  goToPage(currentNum.value);
  isChangeCurrentNum = true;
}

function handleNextPage() {
  currentNum.value =
    currentNum.value + 1 >= numPages.value
      ? numPages.value
      : currentNum.value + 1;
  goToPage(currentNum.value);
  isChangeCurrentNum = true;
}
function goToPage(num) {
  pdfWrap.scrollTo(0, num === 1 ? 0 : pageHeight * num - pageHeight)
  currentNum.value = num
  isChangeCurrentNum = true
}

// 复制地址
function copyToClipboard(text) {
  var textarea = document.createElement("textarea");
  textarea.style.position = "fixed";
  textarea.style.opacity = 0;
  textarea.value = window.location.origin + text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage({
    message: "复制成功",
    type: "success",
  });
}

// 下载地址
function downFile(url, linkDownload) {
  if (!url) {
    ElMessage({
      message: "请输入下载地址",
      type: "warning",
    });
    return;
  }
  fetch(url) //使用fetch函数发送一个GET请求到指定的URL，获取文件的响应对象。
    .then((response) => response.blob()) //通过.then方法链，将响应对象转换为Blob数据（文件的二进制数据）。
    .then((blob) => {
      //再次使用.then方法链，处理获取到的Blob数据。
      const link = document.createElement("a"); //使用document.createElement创建一个<a>节点。
      link.href = URL.createObjectURL(blob); //通过URL.createObjectURL方法，将Blob数据转换成URL对象，然后将该URL赋值给link的href属性。这一步相当于生成了一个临时URL，供下载使用。
      link.download = linkDownload || '隐私政策'; // 替换为你要保存的文件名和扩展名(设置用户下载文件时使用的文件名和扩展名)
      link.click(); //调用click方法模拟用户点击链接，从而触发浏览器的文件下载行为。

      URL.revokeObjectURL(link.href); // 释放URL对象资源(使用URL.revokeObjectURL方法释放之前创建的URL对象资源，避免内存泄漏)
    })
    .catch((error) => {
      console.error("下载失败:", error);
    });
}
</script>

<template>
  <div>
    <div class="home-top" v-if="heightValue >= 40">
      <div class="left">
        版本日期
        <el-select
          v-model="value"
          placeholder="版本日期"
          style="width: 120px; margin-left: 10px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="f">
        <div class="btn" @click="copyToClipboard(copyHtml)">复制地址</div>
        <div class="btn" @click="downFile(`${props.url}`)">下载</div>
      </div>
    </div>
    <div class="overflow-y-scroll" id="pdf" :style="scrollHeight" @scroll="handleScroll">
      <!-- <img class="img" v-for="src in imgSrcList" :key="src" :src="src" :alt="src" /> -->
      <canvas v-for="page in numPages" :id="'the-canvas'+page" :key="page"></canvas>
    </div>
    
    <div v-if="imgSrcList.length !== 0" class="operation-box">
      <div class="operation">
        <div class="page-num-info">
          <span>{{ currentNum }}</span> / <span v-if="!inpDisabled">{{ numPages }}</span>
          <van-loading style="margin-left: 3px; margin-top: 3px" v-else size="14" type="spinner" />
        </div>
        <van-icon @click="handleBeforePage" name="arrow-left" />
        <div class="jump-box" v-if="!inpDisabled">
          <div class="inp-box">
          </div>
        </div>
        <div v-else class="tips">文件正在加载中..跳转功能暂不可用</div>
        <div @click="handleNextPage">下一页 <el-icon><ArrowRightBold /></el-icon></div>
        <div @click="goToPage(1)" class="home" name="wap-home" size="20">首页 <el-icon><Discount /></el-icon></div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px;
  font-size: 12px;
  .left {
    display: flex;
    align-items: center;
  }
  .f {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
  .btn {
    margin-left: 10px;
    line-height: 30px;
    height: 30px;
    border: 1px solid rgb(215, 0, 0);
    border-radius: 30px;
    min-width: 60px;
    padding: 0 10px;
    background: rgb(255, 241, 241);
    color: rgb(215, 0, 0);
  }
}
.overflow-y-scroll{
  overflow-y: scroll;
  overflow: hidden;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  .img{
    // width: 100%;
  }
}
.operation-box {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;

  .operation {
    display: flex;
    align-items: center;
    justify-content: space-around;
    background-color: #404040;
    width: 100%;
    color: #fff;
    padding: 10px 20px;
    border-radius: 30px;
    box-sizing: border-box;

    .jump-box {
      flex: 1;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;

      .inp-box {
        margin-right: 5px;
      }
    }

    .tips {
      flex: 1;
      text-align: center;
      font-size: 14px;
    }

    .page-num-info {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
    }

    .page-num-info,
    .home {
      width: 60px;
      text-align: center;
    }
  }
}
</style>
